import axios from "axios";
import { getToken, removeToken } from "./cookie";
import router from "../router/router";
import { ElMessage } from "element-plus";

// 配置请求头Content-Type默认为application/json
axios.defaults.headers["Content-Type"] = "application/json;charset=utf-8";

// 创建axios实例
const service = axios.create({
    baseURL: "/dev-api",
    timeout: 5000,
});

// request拦截器
service.interceptors.request.use(
    (config) => {
        if (getToken()) {
            config.headers["Authorization"] = getToken();
        }
        return config;
    },
    (error) => {
        console.log(error);
        Promise.reject(error);
    }
)

// response拦截器
service.interceptors.response.use(
    (res) => {
        const code = res.data.code;
        const msg = res.data.msg;
        if (code === 3001) {
            removeToken();
            router.push("/login");
            return Promise.reject(new Error(msg));
        } else if (code !== 1000) {
            ElMessage.error(msg);
            return Promise.reject(new Error(msg));
        } else {
            return Promise.resolve(res.data);
        }
    },
    (error) => {
        ElMessage.error(error);
        return Promise.reject(error);
    }
)
export default service;
